<template>
  <div class="completed-page">
    <div class="completed-header">
      <div class="header-left">
        <button class="back-btn" @click="goToHome">
          <SvgIcon name="back" width="16" height="16" />
        </button>
        <div class="title-group">
          <h1>已完成</h1>
          <span class="subtitle">查看所有已完成的待办事项</span>
        </div>
      </div>
      <div class="header-actions">
        <button class="clear-all-btn" @click="clearAll" :disabled="!hasItems">
          <span class="icon">
            <SvgIcon name="delete" width="16" height="16" color="#ffffff" />
          </span>
          清空记录
        </button>
      </div>
    </div>
    <div class="completed-content">
      <div v-if="loading" class="loading-state">
        <div class="loading-spinner"></div>
        <p>加载中...</p>
      </div>
      <div v-else-if="!hasItems" class="empty-state">
        <SvgIcon name="check-circle" width="64" height="64" />
        <p>没有已完成的待办事项</p>
        <span class="empty-desc">完成的待办事项将会显示在这里</span>
      </div>
      <div v-else class="items-by-category">
        <div
          v-for="group in completedGroups"
          :key="group.labelId"
          class="category-group"
          draggable="true"
          @dragstart="handleCategoryDragStart($event, group.labelId)"
          @dragend="handleCategoryDragEnd($event)"
          @dragover="handleCategoryDragOver($event)"
          @dragleave="handleCategoryDragLeave($event)"
          @drop="handleCategoryDrop($event, group.labelId)"
        >
          <div class="category-header" @click.stop="toggleGroup(group.labelId)">
            <div class="header-left">
              <span class="drag-handle-category">☰</span>
              <h2 class="category-title">{{ group.labelName }}</h2>
              <span class="item-count">{{ group.todoItems.length }}项</span>
            </div>
            <span class="toggle-icon" :class="{ 'is-expanded': isGroupExpanded(group.labelId) }"
              >▼</span
            >
          </div>
          <div class="items-list" v-show="isGroupExpanded(group.labelId)">
            <TodoItem
              v-for="item in group.todoItems"
              :key="item.todoItemId"
              :todo="{
                id: item.todoItemId,
                content: item.content,
                completed: true,
                createdAt: item.createdAt,
                updatedAt: item.updatedAt,
                labelId: group.labelId,
              }"
              @toggle="$emit('toggle', $event)"
              @delete="deleteItem(item)"
              draggable="true"
              @dragstart="handleItemDragStart($event, group.labelId, item.todoItemId)"
              @dragend="handleItemDragEnd($event)"
              @dragover.prevent="handleItemDragOver($event)"
              @dragleave="handleItemDragLeave($event)"
              @drop="handleItemDrop($event, group.labelId, item.todoItemId)"
            >
              <span class="drag-handle">☰</span>
            </TodoItem>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import SvgIcon from '@/components/SvgIcon.vue'
import { useRouter } from 'vue-router'
import { getCompletedTodos, removeTodo, updateCompletedSort } from '@/api/todo'
import { updateCompletedSortLabels } from '@/api/label'
import TodoItem from '@/components/TodoItem.vue'

const router = useRouter()

// 获取所有已完成的待办事项
const completedGroups = ref([])
const loading = ref(true)
const hasItems = computed(() => {
  return completedGroups.value.some((group) => group.todoItems.length > 0)
})

// 跟踪展开的分类
const expandedGroups = ref([])

// 拖拽相关状态
const dragState = ref({
  isDragging: false,
  draggedCategoryId: null,
  draggedItemId: null,
  isDraggingItem: false,
  isDraggingCategory: false,
})

// 分类拖拽开始
const handleCategoryDragStart = (event, categoryId) => {
  dragState.value.isDragging = true
  dragState.value.isDraggingCategory = true
  dragState.value.draggedCategoryId = categoryId

  // 设置拖拽效果和数据
  event.dataTransfer.effectAllowed = 'move'
  event.dataTransfer.setData('text/plain', `category-${categoryId}`)

  // 设置透明度
  event.target.style.opacity = '0.5'
}

// 分类拖拽结束
const handleCategoryDragEnd = (event) => {
  dragState.value.isDragging = false
  dragState.value.isDraggingCategory = false
  event.target.style.opacity = '1'
}

// 分类拖拽进入目标
const handleCategoryDragOver = (event) => {
  if (dragState.value.isDraggingCategory) {
    event.preventDefault()

    // 计算位置
    const rect = event.target.getBoundingClientRect()
    const mouseY = event.clientY

    // 清除之前的样式
    event.target.classList.remove('drag-over-top', 'drag-over-bottom')

    // 添加新样式
    if (mouseY < rect.top + rect.height / 2) {
      event.target.classList.add('drag-over-top')
    } else {
      event.target.classList.add('drag-over-bottom')
    }
  }
}

// 分类拖拽离开目标
const handleCategoryDragLeave = (event) => {
  if (dragState.value.isDraggingCategory) {
    event.target.classList.remove('drag-over-top', 'drag-over-bottom')
  }
}

// 分类放置
const handleCategoryDrop = async (event, targetCategoryId) => {
  if (dragState.value.isDraggingCategory) {
    event.preventDefault()

    // 清除样式
    event.target.classList.remove('drag-over-top', 'drag-over-bottom')

    // 计算位置
    const rect = event.target.getBoundingClientRect()
    const mouseY = event.clientY
    const isTop = mouseY < rect.top + rect.height / 2

    // 源和目标
    const sourceCategoryId = dragState.value.draggedCategoryId

    // 如果源和目标相同，不做任何处理
    if (sourceCategoryId === targetCategoryId) {
      return
    }

    // 找到源和目标的索引
    const sourceCategoryIndex = completedGroups.value.findIndex(
      (group) => group.labelId === sourceCategoryId,
    )
    const targetCategoryIndex = completedGroups.value.findIndex(
      (group) => group.labelId === targetCategoryId,
    )

    // 移除源分类
    const [sourceCategory] = completedGroups.value.splice(sourceCategoryIndex, 1)

    // 计算插入位置
    let insertIndex = targetCategoryIndex
    if (sourceCategoryIndex < targetCategoryIndex && !isTop) {
      insertIndex = targetCategoryIndex
    } else if (sourceCategoryIndex > targetCategoryIndex && isTop) {
      insertIndex = targetCategoryIndex
    } else if (sourceCategoryIndex < targetCategoryIndex && isTop) {
      insertIndex = targetCategoryIndex - 1
    } else if (sourceCategoryIndex > targetCategoryIndex && !isTop) {
      insertIndex = targetCategoryIndex + 1
    }

    // 插入到新位置
    completedGroups.value.splice(insertIndex, 0, sourceCategory)

    // 调用API更新排序
    try {
      const labelIds = completedGroups.value.map((group) => group.labelId)
      const result = await updateCompletedSortLabels(labelIds)

      if (result.success) {
        console.log('标签排序已更新：', labelIds)
      } else {
        console.error('更新标签排序失败:', result.msg)
      }
    } catch (error) {
      console.error('更新标签排序出错:', error)
    }
  }
}

// 待办项拖拽开始
const handleItemDragStart = (event, categoryId, itemId) => {
  dragState.value.isDragging = true
  dragState.value.isDraggingItem = true
  dragState.value.draggedCategoryId = categoryId
  dragState.value.draggedItemId = itemId

  // 设置拖拽效果和数据
  event.dataTransfer.effectAllowed = 'move'
  event.dataTransfer.setData('text/plain', `item-${categoryId}-${itemId}`)

  // 设置透明度
  event.target.style.opacity = '0.5'
}

// 待办项拖拽结束
const handleItemDragEnd = (event) => {
  dragState.value.isDragging = false
  dragState.value.isDraggingItem = false
  event.target.style.opacity = '1'
}

// 待办项拖拽进入目标
const handleItemDragOver = (event) => {
  if (dragState.value.isDraggingItem) {
    event.preventDefault()

    // 计算位置
    const rect = event.target.getBoundingClientRect()
    const mouseY = event.clientY

    // 清除之前的样式
    event.target.classList.remove('drag-over-top', 'drag-over-bottom')

    // 添加新样式
    if (mouseY < rect.top + rect.height / 2) {
      event.target.classList.add('drag-over-top')
    } else {
      event.target.classList.add('drag-over-bottom')
    }
  }
}

// 待办项拖拽离开目标
const handleItemDragLeave = (event) => {
  if (dragState.value.isDraggingItem) {
    event.target.classList.remove('drag-over-top', 'drag-over-bottom')
  }
}

// 待办项放置
const handleItemDrop = async (event, targetCategoryId, targetItemId) => {
  if (dragState.value.isDraggingItem) {
    event.preventDefault()

    // 清除样式
    event.target.classList.remove('drag-over-top', 'drag-over-bottom')

    // 计算位置
    const rect = event.target.getBoundingClientRect()
    const mouseY = event.clientY
    const isTop = mouseY < rect.top + rect.height / 2

    // 源和目标
    const sourceCategoryId = dragState.value.draggedCategoryId
    const sourceItemId = dragState.value.draggedItemId

    // 找到对应的分类和待办项
    const sourceCategoryIndex = completedGroups.value.findIndex(
      (group) => group.labelId === sourceCategoryId,
    )
    const sourceCategory = completedGroups.value[sourceCategoryIndex]

    const sourceItemIndex = sourceCategory.todoItems.findIndex(
      (item) => item.todoItemId === sourceItemId,
    )

    // 如果是同一标签内的排序
    if (sourceCategoryId === targetCategoryId) {
      const targetCategory = sourceCategory
      const targetItemIndex = targetCategory.todoItems.findIndex(
        (item) => item.todoItemId === targetItemId,
      )

      // 移除源项
      const [sourceItem] = targetCategory.todoItems.splice(sourceItemIndex, 1)

      // 计算插入位置
      let insertIndex = targetItemIndex
      if (sourceItemIndex < targetItemIndex && !isTop) {
        insertIndex = targetItemIndex
      } else if (sourceItemIndex > targetItemIndex && isTop) {
        insertIndex = targetItemIndex
      } else if (sourceItemIndex < targetItemIndex && isTop) {
        insertIndex = targetItemIndex - 1
      } else if (sourceItemIndex > targetItemIndex && !isTop) {
        insertIndex = targetItemIndex + 1
      }

      // 插入到新位置
      targetCategory.todoItems.splice(insertIndex, 0, sourceItem)

      // 调用API更新排序
      try {
        const todoItemIds = targetCategory.todoItems.map((item) => item.todoItemId)
        const result = await updateCompletedSort({
          labelId: targetCategoryId,
          todoItemIds,
        })

        if (result.success) {
          console.log('待办项排序已更新：', todoItemIds)
        } else {
          console.error('更新待办项排序失败:', result.msg)
        }
      } catch (error) {
        console.error('更新待办项排序出错:', error)
      }
    }
  }
}

// 切换分类的展开/折叠状态
const toggleGroup = (labelId) => {
  const index = expandedGroups.value.indexOf(labelId)
  if (index === -1) {
    expandedGroups.value.push(labelId)
  } else {
    expandedGroups.value.splice(index, 1)
  }
}

// 判断分类是否展开
const isGroupExpanded = (labelId) => {
  return expandedGroups.value.includes(labelId)
}

// 在组件挂载时获取数据
onMounted(async () => {
  await fetchCompletedTodos()
})

// 获取已完成的待办事项
const fetchCompletedTodos = async () => {
  loading.value = true
  try {
    const result = await getCompletedTodos()
    if (result.success) {
      completedGroups.value = result.data
      console.log('获取已完成待办事项成功:', completedGroups.value)
    } else {
      console.error('获取已完成待办事项失败:', result.msg)
    }
  } catch (error) {
    console.error('获取已完成待办事项出错:', error)
  } finally {
    loading.value = false
  }
}

const goToHome = () => {
  router.push('/')
}

const deleteItem = async (item) => {
  try {
    const result = await removeTodo({ id: item.todoItemId })
    if (result.success) {
      // 从列表中移除该待办
      for (const group of completedGroups.value) {
        group.todoItems = group.todoItems.filter((todo) => todo.todoItemId !== item.todoItemId)
      }
      // 移除空分组
      completedGroups.value = completedGroups.value.filter((group) => group.todoItems.length > 0)
      console.log('删除待办成功')
    } else {
      console.error('删除待办失败:', result.msg)
    }
  } catch (error) {
    console.error('删除待办出错:', error)
  }
}

const clearAll = async () => {
  // 确认对话框
  if (confirm('确定要清空所有已完成的待办事项吗？')) {
    // 遍历所有待办项并删除
    for (const group of completedGroups.value) {
      for (const item of group.todoItems) {
        try {
          await removeTodo({ id: item.todoItemId })
        } catch (error) {
          console.error(`删除待办项 ${item.todoItemId} 失败:`, error)
        }
      }
    }

    // 清空列表
    completedGroups.value = []
    console.log('已清空所有已完成待办事项')
  }
}
</script>

<style scoped>
.completed-page {
  padding: 0;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.completed-header {
  padding: 20px 24px;
  border-bottom: 1px solid #e5e5ea;
  background: #fff;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.back-btn {
  width: 32px;
  height: 32px;
  border-radius: 6px;
  background-color: #f5f5f7;
  border: none;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: background-color 0.2s;
}

.back-btn:hover {
  background-color: #e5e5ea;
}

.title-group {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.header-left h1 {
  font-size: 20px;
  font-weight: 600;
  margin: 0;
  color: #1d1d1f;
}

.subtitle {
  font-size: 13px;
  color: #86868b;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.header-actions button {
  height: 32px;
  padding: 0 16px;
  border-radius: 6px;
  border: none;
  cursor: pointer;
  font-size: 13px;
  display: flex;
  align-items: center;
  gap: 6px;
  transition: all 0.2s;
}

.clear-all-btn {
  background-color: #ff3b30;
  color: white;
}

.clear-all-btn:hover {
  background-color: #ff2d55;
}

.clear-all-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.completed-content {
  flex: 1;
  padding: 24px;
  background-color: #ffffff;
  overflow: hidden;
}

.empty-state,
.loading-state {
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #86868b;
  gap: 12px;
}

.empty-state p,
.loading-state p {
  font-size: 16px;
  margin: 0;
  font-weight: 500;
}

.empty-desc {
  font-size: 14px;
  opacity: 0.8;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 3px solid rgba(67, 97, 238, 0.2);
  border-radius: 50%;
  border-top-color: #4361ee;
  animation: spin 1s ease-in-out infinite;
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

.items-by-category {
  padding: 0 16px;
  height: 100%;
  overflow-y: auto;
  overflow-x: hidden;
  flex: 1;
  scrollbar-width: thin;
  scrollbar-color: #d2d2d7 transparent;
  padding-right: 8px;
  transform: translateZ(0);
}

.items-by-category::-webkit-scrollbar {
  width: 6px;
}

.items-by-category::-webkit-scrollbar-track {
  background: transparent;
}

.items-by-category::-webkit-scrollbar-thumb {
  background-color: #d2d2d7;
  border-radius: 3px;
}

.items-by-category::-webkit-scrollbar-thumb:hover {
  background-color: #86868b;
}

.category-group {
  transition: all 0.3s ease;
  border: 2px solid transparent;
  padding: 4px;
  border-radius: 10px;
  margin-bottom: 16px;
}

/* .category-group:hover {
  background-color: #f5f5f7;
} */

.category-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  cursor: pointer;
  background-color: #f5f5f7;
  border-radius: 8px;
  margin-bottom: 12px;
  transition: background-color 0.2s;
}

.category-header:hover {
  background-color: #e5e5ea;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 8px;
}

.category-title {
  font-size: 16px;
  font-weight: 600;
  color: #1d1d1f;
  margin: 0;
}

.toggle-icon {
  font-size: 12px;
  color: #86868b;
  transition: transform 0.3s;
}

.toggle-icon.is-expanded {
  transform: rotate(180deg);
}

.item-count {
  font-size: 12px;
  color: #86868b;
  background-color: #e5e5ea;
  padding: 2px 8px;
  border-radius: 10px;
}

.items-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
  padding-right: 0;
  width: 100%;
  overflow: hidden;
}

.drag-handle {
  cursor: grab;
  color: #86868b;
  opacity: 0.5;
  margin-right: 8px;
}

.drag-over-top {
  border-top: 2px dashed #4361ee;
}

.drag-over-bottom {
  border-bottom: 2px dashed #4361ee;
}

.drag-handle-category {
  cursor: grab;
  padding: 0 8px;
  color: #86868b;
  font-size: 16px;
  display: inline-block;
  margin-right: 4px;
}

.category-group.drag-over-top {
  border-top: 2px dashed #4361ee;
}

.category-group.drag-over-bottom {
  border-bottom: 2px dashed #4361ee;
}

/* 确保 TodoItem 不会溢出容器 */
.items-list :deep(.todo-item) {
  width: 100%;
  box-sizing: border-box;
}
</style>
